package com.sw.haruka.module.search.manager;

import java.io.File;
import java.util.Collection;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by swsbty on 2021/05/14
 */
public class FileScanManager {

    private Collection<FileScanObserver> observers;
    private ExecutorService service;
    private boolean isScanning = false;

    private static FileScanManager instance = new FileScanManager();

    private FileScanManager() {
        observers = new CopyOnWriteArrayList<>();
        service = Executors.newSingleThreadExecutor();
    }

    public static FileScanManager getInstance() {
        return instance;
    }

    public void scan(String path) {
        service.execute(new Runnable() {
            @Override
            public void run() {
                isScanning = true;
                for (FileScanObserver observer : observers) {
                    observer.scanStart();
                }
                File file = new File(path);
                scanFile(file);
                isScanning = false;
                for (FileScanObserver observer : observers) {
                    observer.scanEnd();
                }
            }
        });
    }

    private void scanFile(File directory) {
        if (!isScanning || !directory.exists() || !directory.isDirectory()) {
            return;
        }
        File[] files = directory.listFiles();
        if (files == null) {
            return;
        }
        for (File file : files) {
            for (FileScanObserver observer : observers) {
                observer.scanned(file);
            }
            if (file.isDirectory()) {
                scanFile(file);
            }
        }
    }

    public void cancel() {
        if (!isScanning) {
            return;
        }
        isScanning = false;
        for (FileScanObserver observer : observers) {
            observer.cancel();
        }
    }

    public void addObserver(FileScanObserver observer) {
        observers.add(observer);
    }

    public void removeObserver(FileScanObserver observer) {
        observers.remove(observer);
    }

}
